package com.ruoyi.web.controller.device.keep;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Keeper;
import com.ruoyi.common.core.domain.entity.Report;
import com.ruoyi.common.core.domain.entity.ReportRecord;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.ReportMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.KeepService;
import com.ruoyi.system.service.ReportRecordService;
import com.ruoyi.system.service.ReportService;
import com.ruoyi.system.service.resp.ReportRecordDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Api("查询维保记录")
@RestController
@RequestMapping("/device/keep/reportRecord")
public class ReportRecordController  extends BaseController {
    @Resource
    private ReportRecordService reportRecordService;
    @Resource
    private KeepService keepService;
    @Resource
    private ReportService reportService;
    @Resource
    private ReportMapper reportMapper;
    @Resource
    private SysUserMapper sysUserMapper;

    @ApiOperation("分页查询维保记录")
    @Log(title = "查询维保记录", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(ReportRecord reportRecord)
    {
        startPage();
        List<ReportRecord> list = reportRecordService.selectKeepList(reportRecord);
        return getDataTable(list);
    }

    @GetMapping("/listNeedMe")
    public TableDataInfo listNeedMe()
    {
        startPage();
        List<Report> list = reportService.selectNeedMeDeviceList(SecurityUtils.getUserId());
        return getDataTable(list);
    }

    @GetMapping("/listNeedMeFinished")
    public TableDataInfo listNeedMeFinished()
    {
        startPage();
        List<Report> list = reportService.selectNeedMeDeviceListFinished(SecurityUtils.getUserId());
        return getDataTable(list);
    }

    @ApiOperation("查询所有维保记录")
    @Log(title = "查询维保记录All", businessType = BusinessType.OTHER)
    @GetMapping("/listAll")
    public TableDataInfo listAll(ReportRecord reportRecord)
    {
        Report report = reportMapper.selectById(reportRecord.getReportId());
        ReportRecord record = new ReportRecord();
        record.setId(report.getId());
        record.setReportId(report.getId());
        record.setStatus(report.getStatus());
        record.setImage(report.getKeepImageUrl());
        record.setKeepImageUrl(report.getKeepImageUrl());
        record.setContent(report.getKeepContent());
        record.setKeeperId(report.getKeeperId());
        record.setUpdateTime(report.getUpdateTime());
        if (report.getKeeperId() == null) {
            return getDataTable(Collections.singletonList(record));
        }
        SysUser sysUser = sysUserMapper.selectUserById(report.getKeeperId());
        record.setKeeperName(Optional.ofNullable(sysUser).map(SysUser::getNickName).orElse(null));
        return getDataTable(Collections.singletonList(record));
    }
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable Long id)
    {
        return success(reportRecordService.selectById(id));
    }

    @ApiOperation("新增维保记录")
    @Log(title = "新增维保记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody ReportRecord reportRecord)
    {
        reportRecord.setCreateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = reportRecordService.createReportRecord(reportRecord);
        if (result) {
            return success();
        }
        return error();
    }

    @ApiOperation("修改维保记录")
    @Log(title = "修改维保记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ReportRecord reportRecord) {
        reportRecord.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        Boolean result = reportRecordService.updateReportRecord(reportRecord);
        if (result) {
            return success();
        }
        return error();
    }

    @ApiOperation("删除维保记录")
    @Log(title = "删除维保记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id)
    {
        return toAjax(reportRecordService.deleteById(id));
    }

    private List<ReportRecordDto> fillToDTO(List<ReportRecord> reportRecords) {
        if (CollectionUtils.isEmpty(reportRecords)) {
            return new ArrayList<>();
        }
        List<Long> keeperIds = reportRecords.stream().map(ReportRecord::getKeeperId).collect(Collectors.toList());

        Map<Long, Keeper> keeperMap = keepService.selectByIds(keeperIds).stream().collect(Collectors.toMap(Keeper::getId, g -> g));
        Report report = reportService.selectById(reportRecords.get(0).getReportId());
        return reportRecords.stream().map(g -> {
            ReportRecordDto reportKeeperDTO = new ReportRecordDto();
            reportKeeperDTO.setId(g.getId());
            reportKeeperDTO.setReportId(g.getReportId());
            reportKeeperDTO.setContent(g.getContent());
            reportKeeperDTO.setKeeperId(g.getKeeperId());
            reportKeeperDTO.setImage(g.getImage());
            reportKeeperDTO.setCreateBy(g.getCreateBy());
            reportKeeperDTO.setCreateTime(g.getCreateTime());
            reportKeeperDTO.setUpdateBy(g.getUpdateBy());
            reportKeeperDTO.setUpdateTime(g.getUpdateTime());
            reportKeeperDTO.setStatus(g.getStatus());
            reportKeeperDTO.setRemark(g.getRemark());
            Keeper keeper = keeperMap.get(g.getKeeperId());
            if (keeper != null) {
                reportKeeperDTO.setKeepName(keeper.getName());
                reportKeeperDTO.setKeepPhone(keeper.getPhone());
            }
            if (report != null) {
                reportKeeperDTO.setCustomerId(report.getId());
            }
            return reportKeeperDTO;
        }).collect(Collectors.toList());
    }
}
